package com.orchard.orchardfarmmanagementsystem.config;

import com.orchard.orchardfarmmanagementsystem.entity.User;
import com.orchard.orchardfarmmanagementsystem.service.UserService;
import com.orchard.orchardfarmmanagementsystem.utils.TokenUtil;
import com.orchard.orchardfarmmanagementsystem.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final UserService userService;

    @Autowired
    public TokenAuthenticationFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String token = resolveToken(request);
        if (token != null && TokenUtil.validateToken(token)) {
            String username = TokenUtil.getUsernameFromToken(token);
            if (username != null) {
                User user = userService.findByUsername(username);
                if (user != null) {
                    List<SimpleGrantedAuthority> authorities = userService.loadUserAuthorities(user.getUserId());

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            user, null, authorities);
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                    // Optionally set the user in a holder for easy access in other services
                    UserHolder.setUser(user);
                }
            }
        }
        chain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}